package com.jzg.sys.common.rest;

import com.jzg.sys.common.util.CommonUtils;
import com.jzg.sys.common.vo.ResultVO;
import com.jzg.sys.dao.entity.*;
import com.jzg.sys.manager.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
 * @description: 所有系统公用的接口，只有登录就有权限访问
 * @author:asxx 李志鹏
 * @create:2019-03-05 10:38
 */
@RestController
@RequestMapping("/commonRest")
public class CommonRest extends BaseRest {
    @Autowired
    private SecMenuManager menuService;
    @Autowired
    private BaseDataManager baseDataService;
    @Autowired
    private BaseFileManager baseFileService;
    @Autowired
    private BaseAreaManager baseAreaService;
    //    @Autowired
//    private RoleService roleService;
    @Autowired
    private SecUserManager userManager;
//    @Autowired
//    private SqlManager sqlManager;

    /**
     * @param sql
     * @return
     * @Title: selectList
     * @Description: 根据sql返回jsonArray
     * @Author: lzp 李志鵬
     * @Date: 2018/6/20
     */
//    @RequestMapping(value = "/selectList")
//    @ResponseBody
//    public JSONArray selectList(String sql) {
//        sql = StringUtils.replace(sql, "\n", " ");
//        return sqlManager.selectList(sql);
//    }

    /**
     * @param sql
     * @return
     * @Title: selectOne
     * @Description: 根据sql返回jsonObject
     * @Author: lzp 李志鵬
     * @Date: 2018/6/20
     */
//    @RequestMapping(value = "/selectOne")
//    @ResponseBody
//    public JSONObject selectOne(String sql) {
//        sql = StringUtils.replace(sql, "\n", " ");
//        return sqlManager.selectOne(sql);
//    }

    /**
     * @param easyPage
     * @param sql
     * @return
     * @Title: selectPage
     * @Description: 分页查询
     * @Author: lzp 李志鵬
     * @Date: 2018/6/21
     */
//    @RequestMapping(value = "/selectPage")
//    @ResponseBody
//    public EasyPage selectPage(EasyPage easyPage,String sql){
//        try {
//            sql = StringUtils.replace(sql, "\n", " ");
//            easyPage = sqlManager.selectPage(easyPage, sql);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return easyPage;
//    }
    @RequestMapping(value = "/menuAllTreeWithRole")
    @ResponseBody()
    public List<SecMenu> menuAllTreeWithRole() {
        try {
            List<SecMenu> list = menuService.findMenuAllTreeWithRole(getCurrUserId(), sysCode);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @return
     * @Title: getNewId
     * @Description: 获取主键，uuid格式
     * @author 李志鹏 lzp
     * @date 2017年8月1日 下午9:09:17
     */
    @RequestMapping(value = "/getNewId")
    @ResponseBody()
    public String getNewId() {
        return CommonUtils.getUUID();
    }

    /**
     * @param size 个数
     * @return
     * @Title: getNewIds
     * @Description: 获取多个主键
     * @Author: lzp 李志鵬
     * @Date: 2018/3/2
     */
    @RequestMapping(value = "/getNewIds")
    @ResponseBody()
    public List<String> getNewIds(Integer size) {
        List<String> ids = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            ids.add(CommonUtils.getUUID());
        }
        return ids;
    }

    @RequestMapping(value = "/findCacheBaseData")
    @ResponseBody
    public List<BaseDataDetail> findCacheBaseData(String dataCode, String type, String exceptDetailCodes) {
        List<BaseDataDetail> bds = new ArrayList<BaseDataDetail>();
        if ("all".equals(type)) {
            BaseDataDetail bd = new BaseDataDetail();
            bd.setDataDetailCode("");
            bd.setDataDetailName("全部");
            bds.add(0, bd);

        }
        if ("empty".equals(type)) {
            BaseDataDetail bd = new BaseDataDetail();
            bd.setDataDetailCode("");
            bd.setDataDetailName("");
            bds.add(0, bd);
        }
        bds.addAll(baseDataService.findCacheBaseData(dataCode, exceptDetailCodes, sysCode));
        return bds;
    }

    /**
     * @param file    文件流
     * @param useCode 文件用途编码
     * @param tableId 业务id
     * @param sortNo
     * @param request
     * @return
     * @Title: fileUpLoad
     * @Description:
     * @author 李志鹏 lzp
     * @date 2017年8月1日 下午1:58:42
     */
    @RequestMapping(value = "/fileUpLoad")
    @ResponseBody
    public ResultVO fileUpLoad(@RequestParam("file") CommonsMultipartFile file,
                               String useCode, String tableId, Long sortNo, HttpServletRequest request) {
        ResultVO vo = new ResultVO(true, "");
        try {
            // 判断文件是否为空
            if (!file.isEmpty()) {
                try {
                    BaseFile baseFile = baseFileService.getBaseFileByCode(useCode, sysCode);
                    if (baseFile == null) {
                        vo.setResult(false);
                        vo.setMsg("没有找到对应的编码:" + useCode);
                        return vo;
                    }
                    BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
                    if (baseFile.getImgWidth() != null && baseFile.getImgHeight() != null) {
                        BigDecimal b = new BigDecimal(bufferedImage.getWidth()).divide(new BigDecimal(bufferedImage.getHeight()), 2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal n = new BigDecimal(baseFile.getImgWidth()).divide(new BigDecimal(baseFile.getImgHeight()), 2, BigDecimal.ROUND_HALF_UP);
                        if (!b.equals(n)) {
                            vo.setResult(false);
                            vo.setMsg("图片不符合要求，请按照" + baseFile.getImgWidth() + "*" + baseFile.getImgHeight() + "上传");
                            return vo;
                        }
                        //压缩
                    }
                    // 文件保存路径
                    String filePath = "upload/" + CommonUtils.getUUID() + "."
                            + FilenameUtils.getExtension(file.getOriginalFilename());
                    file.transferTo(new File(request.getServletContext().getRealPath("/") + filePath));


                    BaseFileDetail baseFileDetail = new BaseFileDetail();
                    baseFileDetail.setFileId(baseFile.getFileId());
                    baseFileDetail.setTableId(tableId);
                    baseFileDetail.setSortNo(sortNo);
                    baseFileDetail.setFileName(file.getOriginalFilename());
                    baseFileDetail.setFileUrl(filePath);
                    baseFileDetail.setStatus(true);
                    baseFileDetail.setSysCode(sysCode);
                    //TODO
//                    baseFileDetail.setInputTime(CommonUtils.getTimeStamp());
                    baseFileService.saveFileDetail(baseFileDetail);
                    // 转存文件
                    vo.setMsg(filePath);
                } catch (Exception e) {
                    e.printStackTrace();
                    vo.setResult(false);
                    vo.setMsg(e.getMessage());
                }
            } else {
                vo.setResult(false);
                vo.setMsg("文件为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            vo.setResult(false);
            vo.setMsg(e.getMessage());
        }
        return vo;
    }


    @RequestMapping(value = "/updateNewPs")
    @ResponseBody
    public ResultVO updateNewPs(String oldPassword, String newPassword) {
        SecUser user = userManager.getById(getCurrUserId());
        if (!DigestUtils.md5Hex(oldPassword).equals(user.getPassword())) {
            return new ResultVO(false, "原密码错误");
        }
        SecUser updateUser = new SecUser();
        updateUser.setUserId(user.getUserId());
        updateUser.setPassword(DigestUtils.md5Hex(newPassword));
        userManager.updateById(updateUser);
        return new ResultVO();
    }


    /**
     * @param useCode
     * @param tableId
     * @return
     * @Title: getImgList
     * @Description: 多图控件获取图片列表
     * @author 李志鹏 lzp
     * @date 2018年1月9日 下午3:08:41
     */
    @RequestMapping(value = "/getImgList")
    @ResponseBody
    public List<BaseFileDetail> getImgList(String useCode, String tableId) {
        return baseFileService.findDetailByTableId(useCode, tableId, getSysCode());
    }

    /**
     * @param useCode
     * @param tableId
     * @param sortNo
     * @return
     * @Title: delImg
     * @Description: 多图控件删除图片
     * @author 李志鹏 lzp
     * @date 2018年1月9日 下午3:11:19
     */
    @RequestMapping(value = "/delImgBySortNo")
    @ResponseBody
    public ResultVO delImgBySortNo(String useCode, String tableId, Long sortNo) {
        baseFileService.delImgBySortNo(useCode, tableId, sortNo, getSysCode());
        return new ResultVO();
    }


    /**
     * @param id
     * @return
     * @Description: 异步树
     */
//    @RequestMapping(value = "/areaTree")
//    @ResponseBody()
//    public List<BaseArea> areaTree(String id) {
//        try {
//            List<BaseArea> list = baseAreaService.findAreaTree(id, "03", getUserAreaCode());
//            return list;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

    /**
     * @param areaCode
     * @param areaCode
     * @return
     * @Title: findAreasByCode
     * @Description: 通过县级code查询出级联下拉所需要的相关省市
     * @author 李志鹏 lzp
     * @date 2017年5月6日 下午3:15:40
     */
//    @RequestMapping(value = "/findAreasForCascader")
//    @ResponseBody()
//    public List<BaseArea> findAreasForCascader(String areaCode) {
//        return baseAreaService.findAreasForCascader(areaCode, getUserAreaCode());
//    }


}
